package com.maikang.exammall.repository;

import com.maikang.exammall.entity.Bill;
import com.maikang.exammall.entity.dto.order.IdOnlyDTO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface BillRepository extends BaseRepository<Bill, Long>, JpaSpecificationExecutor<Bill> {

    Bill findByOutTradeNoAndTransType(String outTradeNo, Integer transType);

    @Query("SELECT bill.status FROM Bill bill WHERE bill.outTradeNo = :outTradeNo AND bill.transType = :transType")
    Integer findStatusByOutTradeNoAndTransType(@Param("outTradeNo") String outTradeNo,
                                               @Param("transType") Integer transType);

    // 选择 交易类型为 下单1， 支付状态为待付款0，已经过了付款时间的单.

    @Query(value = "SELECT id, order_id AS orderId FROM mkb_trade_bill " +
            "WHERE status = 0 " +
            "AND trans_type = 1 " +
            "AND time_expire < CURRENT_TIMESTAMP " +
            "AND create_time > DATE_SUB(curdate(), INTERVAL 7 DAY) AND is_deleted = 0", nativeQuery = true)
    List<IdOnlyDTO> findUnpaidAndExpiredBills();


    @Query("UPDATE Bill bill SET bill.status = :status WHERE bill.id IN (:ids)")
    @Modifying
    void updateStatusByIds(@Param("status") Integer status, @Param("ids") List<Long> ids);
}
